package com.surprise.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HomeController {

	@RequestMapping(value = { "/", "/index" }, method = RequestMethod.GET)
	public String showHomePage() {
		return "index";
	}

	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public ModelAndView upload(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request) throws Exception {

		Map<String, Object> viewModel = new HashMap<String, Object>();
		String filePath = "/home/default/ROOT/movie.mp4";
		//String filePath = request.getServletContext().getRealPath("/") + file.getOriginalFilename();
		if (!file.isEmpty()) {
			file.transferTo(new File(filePath));
		}
		/*
		try {
			filePath = request.getServletContext().getRealPath("/") + "resources/video.html";
			System.out.println("filePath === " + filePath);
			String templateContent = "";
			FileInputStream fileinputstream = new FileInputStream(filePath);
			int lenght = fileinputstream.available();
			byte bytes[] = new byte[lenght];
			fileinputstream.read(bytes);
			fileinputstream.close();
			templateContent = new String(bytes);

			templateContent = templateContent.replaceAll("###src###", file.getOriginalFilename());
			
			String fileName = "/home/default/ROOT/" + file.getOriginalFilename() + ".html";
			//String fileName = request.getServletContext().getRealPath("/") + file.getOriginalFilename() + ".html";
			FileOutputStream fileoutputstream = new FileOutputStream(fileName);
			byte tag_bytes[] = templateContent.getBytes();
			fileoutputstream.write(tag_bytes);
			fileoutputstream.close();
		} catch (Exception e) {
			System.out.print(e.toString());
		}

		String src = "resources/" + file.getOriginalFilename();
		String requestUrl = "http://101.200.228.41/" + file.getOriginalFilename() + ".html";
*/		
		String requestUrl = "http://101.200.228.41/video.html";
		viewModel.put("requestUrl", requestUrl);
		return new ModelAndView("qrcode", viewModel);
	}

	@RequestMapping(value = "/src")
	public ModelAndView resource(@RequestParam(value = "src") String src) {

		Map<String, Object> viewModel = new HashMap<String, Object>();
		viewModel.put("src", src);
		return new ModelAndView("html5", viewModel);
	}

}
